package com.yiwei.jmx.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.library.SuperButton;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.yiwei.jmx.MainActivity;
import com.yiwei.jmx.R;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.IncomeCarBean;
import com.yiwei.jmx.api.bean.UploadImgBean;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.event.CarSelectEvent;
import com.yiwei.jmx.event.LoginSuccessEvent;
import com.yiwei.jmx.util.GlideRoundTransform;
import com.yiwei.jmx.util.GlideUtil;
import com.yiwei.jmx.util.ImageUtil;
import com.yiwei.jmx.util.KeyboardUtil;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.UI;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.SelectMenuDilaog;
import com.yiwei.jmx.view.V19FrameLayout;
import com.yiwei.jmx.view.uploadImage.UploadImgAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class CarIdentityActivity extends BaseActivity implements OnAddressSelectedListener {

    @BindView(R.id.txt_title)
    TextView txtTitle;

    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.btn_select_car_no)
    TextView btnSelectCarNo;
    @BindView(R.id.edit_car_no)
    EditText editCarNo;
    @BindView(R.id.btn_address)
    TextView btnAddress;
    @BindView(R.id.btn_car_type)
    TextView btnCarType;
    @BindView(R.id.btn_car_params)
    TextView btnCarParams;
    @BindView(R.id.img_xingshi)
    ImageView imgXingshi;
    @BindView(R.id.btn_xingshi)
    TextView btnXingshi;
    @BindView(R.id.img_jiashi)
    ImageView imgJiashi;
    @BindView(R.id.btn_jiashi)
    TextView btnJiashi;
    @BindView(R.id.img_zhengmian)
    ImageView imgZhengmian;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;

    private Unbinder unbiner;
    private OptionsPickerView pvOptions;
    private SelectMenuDilaog selectMenuDilaog;
    private UploadImgAdapter uploadImgAdapter;
    private int selectPoi;
    private BottomDialog bottomDialog;
    private String province;
    private String city;
    private String area;
    private KeyboardUtil keyboardUtil;
    private IncomeCarBean submitBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_identity);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        txtTitle.setText("车产认证");

        bottomDialog = new BottomDialog(this);
        bottomDialog.setOnAddressSelectedListener(this);

        selectMenuDilaog = new SelectMenuDilaog(this);
        List<String> data = new ArrayList<>();
        data.add("新车");
        data.add("二手车");
        selectMenuDilaog.setData("car", data);
        selectMenuDilaog.setOnChooseListener(new SelectMenuDilaog.OnChooseListener() {
            @Override
            public void onSuccess(int poi, String text, String menuType) {
                btnCarParams.setText(text);
                submitBean.car_type = text;
            }
        });
        submitBean = new IncomeCarBean();
//        List<String> options1Items = new ArrayList<String>();
//        options1Items.add("粤");
//        options1Items.add("京");
//        options1Items.add("海");
//
//        List<String> data2 = new ArrayList<>();
//        data2.add("A");
//        data2.add("B");
//        data2.add("C");
//        data2.add("D");
//        data2.add("E");
//
//
//        List<List<String>> options2Items = new ArrayList<>();
//        for (int i = 0; i < options1Items.size(); i++) {
//            options2Items.add(data2);
//        }
//
//        pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int option2, int options3, View v) {
//                //返回的分别是三个级别的选中位置
//                String tx = options1Items.get(options1)
//                        + options2Items.get(options1).get(option2);
//                btnSelectCarNo.setText(tx);
//            }
//        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
//            @Override
//            public void onOptionsSelectChanged(int options1, int options2, int options3) {
//                String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
//                ToastUtil.makeText(CarIdentityActivity.this, str);
//            }
//        })
//                .setSubmitText("确认")//确定按钮文字
//                .setCancelText("取消")//取消按钮文字
//                .setTitleText("车牌")//标题
//                .setSubCalSize(15)//确定和取消文字大小
//                .setTitleSize(17)//标题文字大小
//                .setTitleColor(0xff000000)//标题文字颜色
//                .setSubmitColor(0xff0072FF)//确定按钮文字颜色
//                .setCancelColor(0xff0072FF)//取消按钮文字颜色
//                .setTitleBgColor(0xFFF8FBFF)//标题背景颜色 Night mode
//                .setBgColor(0xFFF8FBFF)//滚轮背景颜色 Night mode
//                .setContentTextSize(18)//滚轮文字大小
////                .setLabels("省", "市", "区")//设置选择的三级单位
//                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                .setCyclic(false, false, false)//循环与否
//                .setSelectOptions(1, 1, 1)  //设置默认选中项
//                .setOutSideCancelable(false)//点击外部dismiss default true
//                .isDialog(false)//是否显示为对话框样式
//                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
//                .build();
//
//        pvOptions.setPicker(options1Items, options2Items);//添加数据源
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CarSelectEvent msg) {
        submitBean.carbrand = msg.item.brandName;
        btnCarType.setText(msg.item.brandName);
    }

    public void getUploadImage(Bitmap bitmap) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        UploadImgBean bean = new UploadImgBean();
        bean.img = ImageUtil.Bitmap2StrByBase64(bitmap, 100);
        Api.api_service.getUploadImage(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (selectPoi == 0) {
//                        Glide.with(this).load(result.url).into(imgXingshi);
                        imgXingshi.setImageBitmap(bitmap);
                        submitBean.driving_image = result.url;
                    } else if (selectPoi == 1) {
                        imgJiashi.setImageBitmap(bitmap);
//                        Glide.with(this).load(result.url).into(imgJiashi);
                        submitBean.identity_image = result.url;
                    } else if (selectPoi == 2) {
                        imgZhengmian.setImageBitmap(bitmap);
//                        Glide.with(this).load(result.url).into(imgZhengmian);
                        submitBean.car_image = result.url;
                    }
                });
    }

    public void getCarIdentity() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();

        Api.api_service.getIncomeCarV3(submitBean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "提交车辆信息成功");
                    finish();
                });
    }

    private void initUploadImgAdapter() {
        uploadImgAdapter = new UploadImgAdapter(this, new UploadImgAdapter.Action2() {
            @Override
            public void call(Bitmap file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {
                    getUploadImage(file);
                }
            }

            @Override
            public void callTake(File file, int mode) {

            }
        }, 1);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (uploadImgAdapter != null) {
            uploadImgAdapter.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.btn_select_car_no, R.id.btn_address, R.id.btn_car_type, R.id.btn_car_params, R.id.img_xingshi, R.id.btn_xingshi, R.id.img_jiashi, R.id.btn_jiashi, R.id.img_zhengmian, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_select_car_no:
//                pvOptions.show();
                if (keyboardUtil == null) {
                    keyboardUtil = new KeyboardUtil(this, editCarNo);
                    keyboardUtil.hideSoftInputMethod();
                    keyboardUtil.showKeyboard();
                } else {
                    keyboardUtil.showKeyboard();
                }

                break;
            case R.id.btn_address:
                bottomDialog.show();
                break;
            case R.id.btn_car_type:
                Util.startActivity(this, CarBrandListActivity.class);
                break;
            case R.id.btn_car_params:
                selectMenuDilaog.show();
                break;
            case R.id.img_xingshi:
                selectPoi = 0;
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        if (uploadImgAdapter == null) {
                            initUploadImgAdapter();
                        }
                        uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
                    }

                    @Override
                    public void onReject() {

                    }
                }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
            case R.id.btn_xingshi:
                Util.startActivity(this, CarExampleActivity.class);
                break;
            case R.id.img_jiashi:
                selectPoi = 1;
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        if (uploadImgAdapter == null) {
                            initUploadImgAdapter();
                        }
                        uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
                    }

                    @Override
                    public void onReject() {

                    }
                }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
            case R.id.btn_jiashi:
                Util.startActivity(this, CarExampleActivity.class);
                break;
            case R.id.img_zhengmian:
                selectPoi = 2;
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        if (uploadImgAdapter == null) {
                            initUploadImgAdapter();
                        }
                        uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
                    }

                    @Override
                    public void onReject() {

                    }
                }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
            case R.id.btn_submit:
                String car_text = UI.toString(editCarNo);
                if (car_text.length() < 5) {
                    ToastUtil.makeText(this, "请输入正确的车牌号");
                    return;
                }
                submitBean.carno_prefix = car_text.substring(0, 2);
                submitBean.carno = car_text.substring(2, car_text.length());
                if (submitBean.checkAll()) {
                    getCarIdentity();
                }
                break;
        }
    }

    @Override
    public void onAddressSelected(Province province, City city, County county, Street street) {
        String s =
                (province == null ? "" : province.name) +
                        (city == null ? "" : city.name) +
                        (county == null ? "" : county.name) +
                        (street == null ? "" : street.name);

        if (province != null) {
            this.province = province.name;
            submitBean.province = province.name;
        } else {
            submitBean.province = "";
        }
        if (city != null) {
            this.city = city.name;
            submitBean.city = city.name;
        } else {
            submitBean.city = "";
        }
        if (county != null) {
            if (street != null) {
                area = county.name + street.name;
            } else {
                area = county.name;
            }
        }
//        addressInfo.province = this.province;
//        addressInfo.city = this.city;
//        addressInfo.area = this.area;
        btnAddress.setText(s);


        bottomDialog.dismiss();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (keyboardUtil.isShow()) {
                keyboardUtil.hideKeyboard();
            } else {
                finish();
            }
        }
        return false;
    }

}
